package cn.edu.jsu.zjj.controller;


import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.annotation.Type;
import cn.edu.jsu.zjj.common.DeleteRequest;
import cn.edu.jsu.zjj.common.result.PageResult;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.constant.UserConstant;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.exception.ThrowUtils;
import cn.edu.jsu.zjj.model.dto.ay.AyAddMyRequest;
import cn.edu.jsu.zjj.model.dto.ay.AyQueryRequest;
import cn.edu.jsu.zjj.model.dto.ay.AyUpdateMyRequest;
import cn.edu.jsu.zjj.model.entity.Ay;
import cn.edu.jsu.zjj.service.AyService;
import cn.edu.jsu.zjj.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Yaml;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.Month;
import java.util.List;

/**
 * 学年相关接口
 */
@RestController
@RequestMapping("/ay")
@Slf4j
@Api(tags = "学年管理接口")
public class AyController {
    @Autowired
    private AyService ayService;
    @Autowired
    private UserService userService;

    @ApiOperation("学年分页查询")
    @PostMapping("/page")
    public Result<PageResult> page(@RequestBody AyQueryRequest ayQueryRequest) {
        log.info("学年分页查询，参数为：{}", ayQueryRequest);
        long current = ayQueryRequest.getCurrent();
        long size = ayQueryRequest.getPageSize();
        Page<Ay> ayPage = ayService.page(new Page<>(current, size),
                ayService.getQueryWrapper(ayQueryRequest));
        return Result.success(new PageResult(ayPage.getTotal(), ayPage.getRecords()));
    }

    @ApiOperation("学年全部查询")
    @PostMapping("/list")
    public Result list() {
        LambdaQueryWrapper<Ay> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Ay::getCreateTime);
        List<Ay> ayList = ayService.list(queryWrapper);
        return Result.success(ayList);
    }


    /**
     * 新增学年
     *
     * @param ayAddMyRequest
     * @return
     */
    @Type("新增学年")
    @ApiOperation("新增学年（仅管理员）")
    @PostMapping
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result save(@RequestBody AyAddMyRequest ayAddMyRequest) {
        log.info("新增学年：{}", ayAddMyRequest);
        Ay ay = new Ay();
        ay.setIsDelete(0);
        ay.setUserId(userService.getLoginUser().getId());
        ay.setOperName(userService.getLoginUser().getName());
        // 获取学年的起始年份（基于createTime）
        LocalDate createTime = ayAddMyRequest.getCreateTime();
        int year = createTime.getMonthValue() >= Month.SEPTEMBER.getValue() ? createTime.getYear()
                : createTime.getYear() - 1;
        if (determineSemester(createTime, ayAddMyRequest.getEndTime()) == 1) {
            ay.setTerm(year + "-" + (year + 1) + "-" + "1");
        } else {
            ay.setTerm(year + "-" + (year + 1) + "-" + "2");
        }
        BeanUtils.copyProperties(ayAddMyRequest, ay);
        boolean time = ayService.getTime(ayAddMyRequest.getCreateTime(), ayAddMyRequest.getEndTime());
        if(!time){
            throw new BaseException(MessageConstant.TIME_ERROR);
        }
        boolean timeSelect = ayService.getTimeSelect(ayAddMyRequest.getCreateTime(), ayAddMyRequest.getEndTime());
        if(timeSelect){
            throw new BaseException(MessageConstant.TIME_SELECT_ERROR);
        }
        boolean result = ayService.save(ay);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success();
    }

    /**
     * 编辑学年信息
     * @param ayUpdateMyRequest
     * @return
     */
    @Type("编辑学年信息")
    @ApiOperation("编辑学年信息")
    @PutMapping
    public Result<String> update(@RequestBody AyUpdateMyRequest ayUpdateMyRequest) {
        log.info("编辑学年，请求体为：{}", ayUpdateMyRequest);
        if (ayUpdateMyRequest == null) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        Ay ay = new Ay();
        ay.setUserId(userService.getLoginUser().getId());
        ay.setOperName(userService.getLoginUser().getName());
        BeanUtils.copyProperties(ayUpdateMyRequest, ay);
        ay.setOperName(userService.getLoginUser().getName());
        boolean result = ayService.updateById(ay);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success("更新成功");
    }


    @Type("删除学年")
    @PostMapping("/delete")
    @ApiOperation("删除学年（仅管理员）")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
//    public Result<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BaseException(MessageConstant.PARAMS_ERROR);
//        }
//        boolean b = ayService.removeById(deleteRequest.getId());
//        return Result.success(b);
//    }
    public Result<Boolean> deleteAy(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        return Result.success(ayService.removeById(deleteRequest.getId()));
    }

    /**
     * 根据id查询学年,并且去掉isDelete=1的记录
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询学年")
    @GetMapping("/{id}")
    public Result<AyUpdateMyRequest> getById(@PathVariable Long id) {
        if (id <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }

        Ay ay = ayService.getById(id);
        AyUpdateMyRequest ayUpdateMyRequest = new AyUpdateMyRequest();
        BeanUtils.copyProperties(ay, ayUpdateMyRequest);
        log.info("查询学年，结果为：{}", ayUpdateMyRequest);
        ThrowUtils.throwIf(ay == null, MessageConstant.NOT_FOUND_ERROR);
        return Result.success(ayUpdateMyRequest);
    }


    @ApiOperation("学年学期查询")
    @GetMapping("/terms")
    public Result<List<Ay>> getTerms() {
        List<Ay> terms = ayService.findAllTerms();
        return Result.success(terms);
    }

    /**
     * Determines whether the given time period belongs to the first semester or the second semester.
     *
     * @param createTime the start date of the period
     * @param endTime    the end date of the period
     * @return "第一学期" if the period is in the first semester,
     *         "第二学期" if in the second semester,
     *         "跨学期" if spans both semesters,
     *         "未在学期内" if not within any defined semester
     */
    public static Integer determineSemester(LocalDate createTime, LocalDate endTime) {
        // 定义第一学期和第二学期的起始和结束日期
        // 假设学年从9月开始，第一学期：9月1日到次年1月31日
        // 第二学期：2月1日到6月30日

        // 获取学年的起始年份（基于createTime）
        int year = createTime.getMonthValue() >= Month.SEPTEMBER.getValue() ? createTime.getYear()
                : createTime.getYear() - 1;

        // 定义第一学期和第二学期的起止日期
        LocalDate firstSemesterStart = LocalDate.of(year, Month.SEPTEMBER, 1);
        LocalDate firstSemesterEnd = LocalDate.of(year + 1, Month.JANUARY, 31);

        LocalDate secondSemesterStart = LocalDate.of(year + 1, Month.FEBRUARY, 1);
        LocalDate secondSemesterEnd = LocalDate.of(year + 1, Month.JUNE, 30);

        // 检查时间段是否完全在第一学期
        if (!createTime.isBefore(firstSemesterStart) && !endTime.isAfter(firstSemesterEnd)) {
            return 1;
        }

        // 检查时间段是否完全在第二学期
        if (!createTime.isBefore(secondSemesterStart) && !endTime.isAfter(secondSemesterEnd)) {
            return 2;
        }

        // 检查是否跨越两个学期
        if (createTime.isBefore(secondSemesterStart) && endTime.isAfter(firstSemesterEnd)) {
            return 3;
        }

        // 如果不符合任何学期范围
        return 0;
    }
}
